package com.imooc.demo01;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.UUID;

public class RedisLockTest {

    private int count = 0;
    private String lockKey = "lock";

    /**
     * 多个线程对一个公有变量进行操作，操作结果正常，则这个变量是线程安全的
     *
     * 线程不安全，如果某个key超时，删掉了别人的key，则会造成县城不安全
     * 解决方案：每个key增加唯一标识，只能删除自己的key
     *
     * @param jedis
     */
    private void call(Jedis jedis) {
        // 加锁
        boolean locked = RedisLock.tryLock(jedis, lockKey,
                UUID.randomUUID().toString(), 60);
        try {
            if (locked) {
                for (int i = 0; i < 500; i++) {
                    count++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisLock.unlock(jedis, lockKey);
        }
    }

    public static void main(String[] args) throws Exception {
        RedisLockTest redisLockTest = new RedisLockTest();
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(1);
        jedisPoolConfig.setMaxTotal(5);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,
                "127.0.0.1", 6379, 1000);

        Thread t1 = new Thread(() -> redisLockTest.call(jedisPool.getResource()));
        Thread t2 = new Thread(() -> redisLockTest.call(jedisPool.getResource()));
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(redisLockTest.count);
    }

}